package com.ruiben.mall.controller;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.jpay.ext.kit.HttpKit;
import com.jpay.ext.kit.IpKit;
import com.jpay.ext.kit.PaymentKit;
import com.jpay.weixin.api.WxPayApi;
import com.jpay.weixin.api.WxPayApiConfig;
import com.jpay.weixin.api.WxPayApiConfigKit;
import com.ruiben.mall.impl.OrderServiceImpl;
import com.ruiben.mall.impl.PayServiceImpl;
import com.ruiben.mall.impl.UserServiceImpl;
import com.ruiben.mall.pojo.UserOrder;
import com.ruiben.mall.utils.*;
import com.ruiben.mall.vo.H5ScencInfo;
import com.ruiben.mall.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("pay")
public class PayController extends BaseController {

    @Autowired
    private OrderServiceImpl orderService;

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private PayServiceImpl payService;


    @PostMapping("balancePay")
    public CommonJSONResult balancePay(String userId,String orderId,String orderNo, BigDecimal total){

        if (StringUtils.isBlank(userId)){
            return CommonJSONResult.errorMsg("用户id不能为空");
        }

        if (StringUtils.isBlank(orderId)){
            return CommonJSONResult.errorMsg("订单id不能为空");
        }

        if (StringUtils.isBlank(orderNo)){
            return CommonJSONResult.errorMsg("订单号不能为空");
        }

        if (total == null) {
            return CommonJSONResult.errorMsg("支付金额不能为空");
        }

        UserVo userInfo = userService.getUserInfo(userId);
        UserOrder userOrder = orderService.getOrderById(orderId,orderNo);
        if (userOrder == null){
            return CommonJSONResult.errorMsg("没有相关订单");
        }

        //用户余额
        BigDecimal userMoney = new BigDecimal(userInfo.getUserMoney());

        //商品总价
        BigDecimal sumprice = userOrder.getSumprice();

        if (total.compareTo(sumprice) != 0) {
            return CommonJSONResult.errorMsg("支付金额不相符");
        }

        if (userMoney.compareTo(sumprice) <= 0){
            return CommonJSONResult.errorMsg("余额不足");
        }


        boolean b = payService.balancePay(userId, orderId);
        if (b){
            return CommonJSONResult.ok();
        }

        return CommonJSONResult.errorMsg("支付失败");


    }


    @PostMapping("wxPay")
    public CommonJSONResult wxPay(String productName, String out_trade_no, String total_fee){

        //需要传递的参数有：body:商品描述   out_trade_no ：商户订单号  total_fee：总金额
        //传req 主要是为了获取ip地址
        //注意：1.有个ip地址我是写的固定的，可以返回成功
        //     2.注意回调地址，必须是外网可访问的地址
        try {
            //创建map集合，实现参数存储
            Map<String, String> reqData = new HashMap<String, String>();
            PropConfig prop = new PropConfig();
            reqData.put("appid", prop.get("appId"));
            reqData.put("mch_id", prop.get("mchId"));
            reqData.put("nonce_str", WXPayUtil.generateNonceStr());//32位随机字符串
            reqData.put("sign_type", WXPayConstants.MD5);
            if(!StringUtils.isBlank(productName)) {
                productName = productName.replaceAll(" ", "");
                productName = productName.length() > 17 ? productName.substring(0, 17) + "..." : productName;
                reqData.put("body",productName);
            }
            if(!StringUtils.isBlank(out_trade_no)) {
                reqData.put("out_trade_no", out_trade_no);
            }
            if(!StringUtils.isBlank(total_fee)) {
                reqData.put("total_fee", total_fee);
            }
            reqData.put("spbill_create_ip","123.56.28.148");
            reqData.put("notify_url", prop.get("notify_url"));  //这个回调地址在propeties中，还需确定回调方法
            reqData.put("trade_type", prop.get("trade_type"));

            reqData.put("sign", WXPayUtil.generateSignature(reqData, prop.get("paySignKey"), WXPayConstants.SignType.MD5));//生成签名

            //集合转化为xml ======再转换成string
            String output = WXPayUtil.mapToXml(reqData).toString();


            String xmltomap = WXPayRequest.httpsRequest(prop.get("unifiedorder"), "POST", output);

            Map<String, String> stringMap = WXPayUtil.xmlToMap(xmltomap);

            //返回的code_url
            String codeUrl = stringMap.get("code_url");
            System.out.println("支付地址："+codeUrl);

            return CommonJSONResult.ok(codeUrl);

        }catch (Exception e){
            e.printStackTrace();
        }

        return CommonJSONResult.errorMsg("支付错误");
    }


    @RequestMapping(value = "wxPayNotify",produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String wxPayNotify (HttpServletRequest request) throws Exception {

        System.out.println("微信支付回调");
        InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        if (inStream !=null){
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            String resultxml = null;

            resultxml = new String(outSteam.toByteArray(), "utf-8");

            Map<String, String> params = doXMLParse(resultxml);
            outSteam.close();
            inStream.close();

//        System.out.println(params);

            Map<String,String> return_data = new HashMap<String,String>();
            System.out.println("===============付款成功==============");
            String success = params.get("return_code");
            if (success.equals("SUCCESS")) {
                String out_trade_no = String.valueOf(params.get("out_trade_no").split("O")[0]);
                UserOrder orderByOrderNo = orderService.getOrderByOrderNo(out_trade_no);
                orderByOrderNo.setOrderstatus((short)2);
                orderService.updateOrder(orderByOrderNo);
                System.out.println("这里已经付款成功");
            }
            // ------------------------------
            // 处理业务开始
            // ------------------------------
            // 此处处理订单状态，结合自己的订单数据完成订单状态的更新
            // ------------------------------

//        String total_fee = params.get("total_fee");
//        double v = Double.valueOf(total_fee) / 100;
//        String out_trade_no = String.valueOf(params.get("out_trade_no").split("O")[0]);
//        Date accountTime = DateUtil.stringtoDate(params.get("time_end"), "yyyyMMddHHmmss");
//        String ordertime = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");
//        String totalAmount = String.valueOf(v);
//        String appId = params.get("appid");
//        String tradeNo = params.get("transaction_id");

//        return_data.put("return_code", "SUCCESS");
//        return_data.put("return_msg", "OK");
            return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        }

        //如果失败返回错误，微信会再次发送支付信息
        return "fail";

    }


    //xml解析
    public static Map doXMLParse(String strxml) throws JDOMException, IOException {
        strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");

        if(null == strxml || "".equals(strxml)) {
            return null;
        }

        Map m = new HashMap();

        InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(in);
        Element root = doc.getRootElement();
        List list = root.getChildren();
        Iterator it = list.iterator();
        while(it.hasNext()) {
            Element e = (Element) it.next();
            String k = e.getName();
            String v = "";
            List children = e.getChildren();
            if(children.isEmpty()) {
                v = e.getTextNormalize();
            } else {
                v = getChildrenText(children);
            }

            m.put(k, v);
        }

        //关闭流
        in.close();

        return m;
    }




    public static String getChildrenText(List children) {
        StringBuffer sb = new StringBuffer();
        if(!children.isEmpty()) {
            Iterator it = children.iterator();
            while(it.hasNext()) {
                Element e = (Element) it.next();
                String name = e.getName();
                String value = e.getTextNormalize();
                List list = e.getChildren();
                sb.append("<" + name + ">");
                if(!list.isEmpty()) {
                    sb.append(getChildrenText(list));
                }
                sb.append(value);
                sb.append("</" + name + ">");
            }
        }

        return sb.toString();
    }


    public static WxPayApiConfig getApiConfig() {

        PropConfig prop = new PropConfig();

        return WxPayApiConfig.New()
                .setOpenId("312312313")
                .setAppId(prop.get("appId"))
                .setMchId(prop.get("mchId"))
                .setPaternerKey(prop.get("paySignKey"))
                .setNonceStr(String.valueOf(System.currentTimeMillis()))
                .setTimestamp(String.valueOf(System.currentTimeMillis() / 1000L))
                .setPayModel(WxPayApiConfig.PayModel.BUSINESSMODEL);
    }


    public  String getAccessToken() {
        PropConfig prop = new PropConfig();
        String access_token = "";
        String grant_type = "client_credential";//获取access_token填写client_credential
        String AppId=prop.get("appId");//第三方用户唯一凭证
        String secret="23ac4e33eb5e3dd9c6d0100cecc14af5";//第三方用户唯一凭证密钥，即appsecret
        //这个url链接地址和参数皆不能变
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type="+grant_type+"&appid="+AppId+"&secret="+secret;

        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String message = new String(jsonBytes, "UTF-8");
            JSONObject demoJson = JSONObject.parseObject(message);
            System.out.println("JSON字符串："+demoJson);
            access_token = demoJson.getString("access_token");
            System.out.println("微信token:"+access_token);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return access_token;
    }


    public String getTicket(String access_token) {
        String ticket = null;
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+ access_token +"&type=jsapi";//这个url链接和参数不能变
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String message = new String(jsonBytes, "UTF-8");
            JSONObject demoJson = JSONObject.parseObject(message);
            System.out.println("JSON字符串："+demoJson);
            ticket = demoJson.getString("ticket");
            redis.set(TICKET,ticket,7000);

            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ticket;
    }


    public  String SHA1(String decript) {
        try {
            MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
            digest.update(decript.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    @PostMapping("getSignature")
    public String getSignature( String noncestr,String timestamp){
        String jsapi_ticket = "";
        if (StringUtils.isNotBlank(redis.get(TICKET))){
            jsapi_ticket =  redis.get(TICKET);
        } else {
            //1、获取AccessToken
            String accessToken = getAccessToken();

            //2、获取Ticket
            jsapi_ticket = getTicket(accessToken);
        }

        //3、时间戳和随机字符串
//        String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);//随机字符串
//        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);//时间戳


        //4、获取url
        String url="http://yingyu.yuzhekeji.top:8088/payMode";
    /*根据JSSDK上面的规则进行计算，这里比较简单，我就手动写啦
    String[] ArrTmp = {"jsapi_ticket","timestamp","nonce","url"};
    Arrays.sort(ArrTmp);
    StringBuffer sf = new StringBuffer();
    for(int i=0;i<ArrTmp.length;i++){
        sf.append(ArrTmp[i]);
    }
    */

        //5、将参数排序并拼接字符串
        String str = "jsapi_ticket="+jsapi_ticket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+url;

        //6、将字符串进行sha1加密
        String signature =SHA1(str);
        System.out.println("参数："+str+"\n签名："+signature);


        return signature;
    }


    /**
     * 微信H5 支付--------------------好使
     * 注意：必须再web页面中发起支付且域名已添加到开发配置中
     */
    @PostMapping(value ="/wxphonepay")
    public CommonJSONResult wapPay(HttpServletRequest request,HttpServletResponse response,String productName, String out_trade_no, String total_fee) throws Exception{
        WxPayApiConfig wxPayApiConfig=getApiConfig();
        String signature = getSignature(wxPayApiConfig.getNonceStr(),wxPayApiConfig.getTimestamp());


        System.out.println("--pay start--");
        String notify_url = "http://yingyu.yuzhekeji.top:8080/pay/pay_notify";//这是回调地址，方法在下面
        //获取ip
        String ip = IpKit.getRealIp(request);
        if (com.jpay.ext.kit.StrKit.isBlank(ip)) {
            ip = "127.0.0.1";
        }

        H5ScencInfo sceneInfo = new H5ScencInfo();

        H5ScencInfo.H5 h5_info = new H5ScencInfo.H5();
        h5_info.setType("Wap");
        //此域名必须在商户平台--"产品中心"--"开发配置"中添加

        h5_info.setWap_url("http://yingyu.yuzhekeji.top");
        h5_info.setWap_name("公司官网");
        sceneInfo.setH5_info(h5_info);

        PropConfig prop = new PropConfig();
        Map<String, String> params=WxPayApiConfig.New()
                .setOpenId(wxPayApiConfig.getOpenId())
                .setAppId(wxPayApiConfig.getAppId())
                .setMchId(wxPayApiConfig.getMchId())
                .setBody("H5支付测试")
                .setSpbillCreateIp(ip)
                .setTotalFee("1")
                .setTradeType(WxPayApi.TradeType.JSAPI)
                .setNotifyUrl(notify_url)
                .setPaternerKey(prop.get("paySignKey"))
                .setOutTradeNo(String.valueOf(System.currentTimeMillis()))
                .setSceneInfo("{\"h5_info\": {\"type\":\"IOS\",\"app_name\": \"mtgg\",\"package_name\": \"com.tencent.tmgp.sgame\"}}")
                .setAttach("H5支付测试")
                .build();
        String xmlResult = WxPayApi.pushOrder(false,params);
        Map<String, String> result = PaymentKit.xmlToMap(xmlResult);
        //返回结果
        String return_code = result.get("return_code");
        String return_msg = result.get("return_msg");
        if (!PaymentKit.codeIsOK(return_code)) {
            System.out.println("return_code>"+return_code+" return_msg>"+return_msg);
            throw new RuntimeException(return_msg);
        }
        String result_code = result.get("result_code");
        if (!PaymentKit.codeIsOK(result_code)) {
            System.out.println("result_code>"+result_code+" return_msg>"+return_msg);
            throw new RuntimeException(return_msg);
        }
        // 以下字段在return_code 和result_code都为SUCCESS的时候有返回

        String prepay_id = result.get("prepay_id");
        String mweb_url = result.get("mweb_url");

        System.out.println("prepay_id:"+prepay_id+" mweb_url:"+mweb_url);
//        try {
//            response.sendRedirect("http://www.baidu.com");
////            request.getRequestDispatcher(mweb_url).forward(request,response);
//            System.out.println("跳 转了："+mweb_url);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        Map<String,String > resultMap = new HashMap<>();
        resultMap.put("package","prepay_id=" + prepay_id);

//        Map<String,String> signMap = new HashMap<>();
//        signMap.put("appid")
//        WXPayUtil.(reqData, prop.get("paySignKey"), WXPayConstants.SignType.MD5)


//        String a = "appId="+wxPayApiConfig.getAppId()+"&nonceStr="+wxPayApiConfig.getNonceStr()+"&package=prepay_id="+prepay_id+"&signType=MD5&timeStamp="+wxPayApiConfig.getTimestamp()+"&key=123456jkldjfldkaljfldjfkeimkvjid";
        Map<String, String> reqData = new HashMap<String, String>();
        reqData.put("appId", wxPayApiConfig.getAppId());
        reqData.put("nonceStr", wxPayApiConfig.getNonceStr());
        reqData.put("package", "prepay_id="+prepay_id);//32位随机字符串
        reqData.put("signType", WXPayConstants.MD5);
        reqData.put("timeStamp", wxPayApiConfig.getTimestamp());

        String sign = WXPayUtil.generateSignature(reqData, "123456jkldjfldkaljfldjfkeimkvjid", WXPayConstants.SignType.MD5);//生成签名

//        System.out.println("当前的这个串：" + sign);
//        String paySign=MD5Utils.getMD5Str(a).toUpperCase();
        System.out.println("当前这个串md5:" + sign);
        resultMap.put("paySign",sign);


        resultMap.put("signature",signature);
        resultMap.put("nonceStr",wxPayApiConfig.getNonceStr());
        resultMap.put("timeStamp",wxPayApiConfig.getTimestamp());
        resultMap.put("appId",wxPayApiConfig.getAppId());

        return CommonJSONResult.ok(resultMap);
    }


    @RequestMapping(value = "/pay_notify",method={RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public void pay_notify(HttpServletRequest request,HttpServletResponse response) {
        // 支付结果通用通知文档: https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_7
        System.out.println("---------------支付回调----------------");
        String xmlMsg = HttpKit.readData(request);
        System.out.println("pay notice---------"+xmlMsg);
        Map<String, String> params = PaymentKit.xmlToMap(xmlMsg);
//		String appid  = params.get("appid");
//		//商户号
//		String mch_id  = params.get("mch_id");
        String result_code  = params.get("result_code");
//		String openId      = params.get("openid");
//		//交易类型
//		String trade_type      = params.get("trade_type");
//		//付款银行
//		String bank_type      = params.get("bank_type");
//		// 总金额
        String total_fee     = params.get("total_fee");
        total_fee = total_fee.substring(0,total_fee.length()-2);
//		//现金支付金额
//		String cash_fee     = params.get("cash_fee");
//		// 微信支付订单号
//		String transaction_id      = params.get("transaction_id");
//		// 商户订单号
//		String out_trade_no      = params.get("out_trade_no");
//		// 支付完成时间，格式为yyyyMMddHHmmss
//		String time_end      = params.get("time_end");

        /////////////////////////////以下是附加参数///////////////////////////////////

        String account      = params.get("attach");
        System.out.println("回调total_fee-->"+total_fee);
        System.out.println("回调account-->"+account);
//		String fee_type      = params.get("fee_type");
//		String is_subscribe      = params.get("is_subscribe");
//		String err_code      = params.get("err_code");
//		String err_code_des      = params.get("err_code_des");
        // 注意重复通知的情况，同一订单号可能收到多次通知，请注意一定先判断订单状态
        // 避免已经成功、关闭、退款的订单被再次更新
//		Order order = Order.dao.getOrderByTransactionId(transaction_id);
//		if (order==null) {
        String resXml = "";
        WxPayApiConfigKit.setThreadLocalWxPayApiConfig(getApiConfig());
        if(PaymentKit.verifyNotify(params, WxPayApiConfigKit.getWxPayApiConfig().getPaternerKey())){
            if (("SUCCESS").equals(result_code)) {
                // TODO 根据商户订单号更改押金状态
                System.out.println("成功，存储");

                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                        + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";

            } else {
                //TODO FAIL支付失败
//                log.debug("支付失败的回调消息");
                System.out.println("支付失败的回调消息");
                resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                        + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";

            }
            BufferedOutputStream out = null;
            try {
                out = new BufferedOutputStream(
                        response.getOutputStream());
                out.write(resXml.getBytes());
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
//		}

    }

    @PostMapping("aliPay")
    public void aliPay(HttpServletRequest httpRequest,
                       HttpServletResponse httpResponse) throws ServletException, IOException {

        String APP_ID = "2016091700530287";
        String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDYAZGXTt+cgPLgOCs+Fhpb3u1NbjfkqzBVvic5PSlv4jL26PFohOrr0Tcm9M4neo1ywLFfVgf2RO1+h/b8ewU0zMv9kP/y6kDG7N3TKxnvAcEGYqWdoNq3vpTEHuVi4PZxfIhao9o7ENys7jmTboVyR22Kq6F6HNY/XXRw0DiwXV354l0uNzjioMwY12FWcvxTED579tRhjkBnktgJZV/IjfR/Rpi5mA9kdFOzkJXZVfk8DlicBnXRWazYlhbjB/ShitHic0K0SO0AUYEbWrhUaDAyN1j/5uSaHW8C22R9gTtdtSNmJz/n7cESlvGz855GYUnIW5PIbg3YZP4c+l/fAgMBAAECggEBAIq2hy5pokO4sz+2El7uhsLUqAN/cjlQjduiH0Isur10v1G8SbrbEJmbYxWLRBAqLUex4rXcY4SMww7sdXmx7qf3lFAjm5n9QNf+KH2BQkgwEirtknllYM96fcJsLNaQrPI4DMBYVL51l6Ed4q+A3AWFRR02Fp56gkNy2mHP9Xebbr8TiyQkb4whad/iBJCdPq6wBhJmZTrtGe6l+sG7VP82UF2m3z82aFHx+xZ59zthBVgY05Q5R11mTF8/jhQrZRQLhUp13nFxuCzFvwPBsdpaYlt6vc+wpKPuUaIBakrpvSIL4+5Xuit+RohoTSZ7ZA2+W00X6v8NnTd8nuHVfqECgYEA/13Q8A8bm5XzQjBvkPDiZ9JWLHSo7mCWMI4s0Wam2hphXFtBorIoBIT4pBlCQ+fmDsBwCbLBlgDgtQZWMubwKZkLkL64PGEbsLzzgvr+U9JQ8S/lbgvm2XiFbGEu7BwpzAQXi6NS/ApRlzUIvmNNaK9hNcdW/jwi1Or1TmwvrIcCgYEA2IrBNId6lKuygJGnTayD9/soI8zCwD75kLI89WYcSjlUAEpSOzOytm39Hwx5Ll//DTVyRVe6Jx/wp36sLiwKZ0RMozfuNj/O4bABknnxnikWCZQnc714qb4MnrB/RfnvHW2uu/bgIrUCxIvlJoMYuHXJKyiMb75jTv03S/E+H+kCgYEA5KzfUElHILFLz8bN8U40gGIzdsXVDPoDJGH8slupKIAdFXZGtWmyOjHU8iYIWATO2ADtk1G21xvcHV8aS6TQBYAegjS3iKIxCLh7m5wlqWwZvZF1c3FG/RFW8XGpchfaOe6kIxBTXI3k+HGubcdA53C9rUnflfTGAEKS/vIUUvsCgYACS95mpzUmlHeNI35JtZWksJYpYweBsGlHHozE8XNFWjxI0ID0vcScaKgxhxlV45C53CI9GAQSXCVaMV60EqV9mNzTMkmla6HPBOXPXtmwGrFwIpEUiiLYcfqCSE7hOBhQEJS0y5Zu58qCuRUSBnvhoOYkPgbXPIajFM5cUM+e2QKBgA0ha9HZ+6qDX7m9QuOHwJJpLHzp7vcfQr2rnMIjNI1XXB/lgqaedd3SZnkOfTjrZ/MwEGsOjoh+Fz5fU8GJ0LLYZcmoRFEjLzya4C4/CQ53RwI9QEslf4xmIlWUxCEMhhIebnYuuCsFYpndeggfKYqVGKWq7aJHpoKJOGR2jqYP";
        String FORMAT = "json";
        String CHARSET = "UTF-8";
        String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2AGRl07fnIDy4DgrPhYaW97tTW435KswVb4nOT0pb+Iy9ujxaITq69E3JvTOJ3qNcsCxX1YH9kTtfof2/HsFNMzL/ZD/8upAxuzd0ysZ7wHBBmKlnaDat76UxB7lYuD2cXyIWqPaOxDcrO45k26FckdtiquhehzWP110cNA4sF1d+eJdLjc44qDMGNdhVnL8UxA+e/bUYY5AZ5LYCWVfyI30f0aYuZgPZHRTs5CV2VX5PA5YnAZ10Vms2JYW4wf0oYrR4nNCtEjtAFGBG1q4VGgwMjdY/+bkmh1vAttkfYE7XbUjZic/5+3BEpbxs/OeRmFJyFuTyG4N2GT+HPpf3wIDAQAB";
        String SIGN_TYPE = "RSA2";
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do", APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE); //获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request
        alipayRequest.setReturnUrl("http://domain.com/CallBack/return_url.jsp");
        alipayRequest.setNotifyUrl("http://domain.com/CallBack/notify_url.jsp");//在公共参数中设置回跳和通知地址
        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":\"20150320010101001\"," +         //订单号
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +      //即时到账业务？？？？
                "    \"total_amount\":88.88," +             //商品金额
                "    \"subject\":\"Iphone6 16G\"," +        //商品名称
                "    \"body\":\"Iphone6 16G\"," +           //商品描述
                "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," +    //这个可以注释，注释不影响结果
                "    \"extend_params\":{" +          //这个不能注释，注释显示：抱歉，系统网络繁忙，您暂时无法付款，请稍后再试。
                "    \"sys_service_provider_id\":\"2088511833207846\"" +  //这个不能注释，注释显示联系卖家
                "    }" +
                "  }");//填充业务参数
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }


        httpResponse.setContentType("text/html;charset=" + CHARSET);

        httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();



    }

}
